#include <bits/stdc++.h>
using namespace std;
const long long int N = 1e4;
const long long int INF = 1e9+10;
const long long int row = 1e9;
const long long int col = 1e9;
pair<int, int> src, dest;
//bool vis[N][N] = {false};
map <pair<int,int>, bool> vis;
//long long int level[N][N];
map <pair<int,int>, int> level;
map <pair<int,int>, bool> allowed;
bool isvalid(int x, int y){
return x>=0 and y >=0 and x <= row and y <= col and allowed[{x, y}];
}
vector <pair<int, int>> movements = {
{1,0}, {-1,0}, {0,1}, {0,-1},
{-1, -1}, {1, 1}, {1,-1}, {-1,1}
};
int bfs(pair<int, int>p1, pair<int, int> p2){
int source_x = p1.first;
int source_y = p1.second;
int dest_x = p2.first;
int dest_y = p2.first;
level[{source_x, source_y}] = 0;
vis[{source_x, source_y}] = true;
queue <pair<int, int>> q;
q.push({source_x, source_y});
while(!q.empty()){
pair <int, int> p = q.front();
q.pop();
int x = p.first;
int y = p.second;
bool check = false;
/*
for(auto move:movements)
{
int check_x = move.first + x;
int check_y = move.first + y;
check = check | isvalid(check_x, check_y);
}
if(!check){
return -1;
}*/
for(auto move: movements){
int newx = move.first + x;
int newy = move.second + y;
if(!isvalid(newx, newy)) continue;
if(!vis[{newx, newy}]){
q.push({newx, newy});
level[{newx,newy}] = level[{x,y}] +1;
vis[{newx,newy}] = true;
if(newx == dest.first and newy == dest.second){
return level[{newx, newy}];
}
}
}
}
return level[{dest.first, dest.second}];
}
int main(){
long long int s1, s2, d1, d2;
cin >> s1 >> s2 >> d1 >> d2;
src.first = s1;
src.second = s2;
dest.first = d1;
dest.second = d2;
int n; cin >> n;
for(int i = 0; i < n; i++){
long long int r, a, b;
cin >> r >> a >> b;
for(int j = a;j <= b; j++){
allowed[{r, j}] = true;
}
}
int ans = bfs(src, dest);
if(ans == 0){
if(src.first == dest.first and src.second == dest.second){
cout << 0 << endl;
}else{
cout << -1 << endl;
}
}
else
{
cout << ans << endl;
}
}
987. Vertical Order Traversal of a Binary Tree | 952. Largest Component Size by Common Factor |
212. Word Search II | 174. Dungeon Game |
127. Word Ladder | 123. Best Time to Buy and Sell Stock III |
85. Maximal Rectangle | 84. Largest Rectangle in Histogram |
60. Permutation Sequence | 42. Trapping Rain Water |
32. Longest Valid Parentheses | Cutting a material |
Bubble Sort | Number of triangles |
AND path in a binary tree | Factorial equations |
Removal of vertices | Happy segments |
Cyclic shifts | Zoos |
Build a graph | Almost correct bracket sequence |
Count of integers | Differences of the permutations |
Doctor's Secret | Back to School |
I am Easy | Teddy and Tweety |
Partitioning binary strings | Special sets |